package com.sunshine.androidjavapractise.ui.activity.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.sun.androidexerciseproject.model.IMyAidlInterface;
import com.sunshine.androidjavapractise.R;
import com.sunshine.androidjavapractise.decode.DecodeTest;
import com.sunshine.androidjavapractise.pattern.singleton.EnumSingleton;
import com.sunshine.androidjavapractise.test.TestSingleInstance;
import com.sunshine.androidjavapractise.thread.ThreadPool;
import com.sunshine.androidjavapractise.thread.ThreadPoolManager;
import com.sunshine.androidjavapractise.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    static final int PICK_CONTACT_REQUEST = 1;

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private IMyAidlInterface mAidlInterface;
    private ThreadPoolManager mPoolManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testSeparator();
        // Example of a call to a native method
        Button btnChangeText = findViewById(R.id.btn_change_text);
        btnChangeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                saveUserInfo();
//                if (null != mAidlInterface) {
//                    try {
//                        List<Book> bookList = mAidlInterface.getBookList();
//                        for (Book book : bookList) {
//                            Log.d("sun", book.getName());
//                        }
//                        mAidlInterface.addBook(new Book("周恩来"));
//                        Log.d("sun", "add later\n");
//                        bookList = mAidlInterface.getBookList();
//                        for (Book book : bookList) {
//                            Log.d("sun", book.getName());
//                        }
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
//                }
//                testMultiThread();
//                base64Test();
//                singletonTest();
//                pickContact();
            }
        });
        mPoolManager = ThreadPoolManager.getSingleton();
        mPoolManager.init(this);
        mPoolManager.init(this);
        bindService();
    }

    private void base64Test() {
        String ret = DecodeTest.decode("eyJmbGFnIjpmYWxzZSw&bWVzc2FnZSI6Imh0dHA6Ly8xOTIuMTY4LjMuNDkvc2VydmljZXMvZ2V0Q2hhbm5lbEluZm8vZ2V0VXNpbmdD*GFubmVsSW5mb0J5QXBwSWRBbmRQcm9kdWN0VHlwZUNvZGVBbmRUeXBlQ29kZS82ODAxNzEwNDQ2ODQwMy9*RkJ*WlNES1NNLzM&LCJjb2RlIjotOTIwMDB9");
        if (!TextUtils.isEmpty(ret)) {
            System.out.println("ret = " + ret);
        }
    }

//    private void saveUserInfo() {
//        MyApplication myApplication = (MyApplication) getApplication();
//        DaoSession daoSession = myApplication.getDaoSession();
//        UserDao userDao = daoSession.getUserDao();
//        User user = new User();
//        user.setId(1);
//        user.setAge(33);
//        user.setName("小明");
//        userDao.insertOrReplace(user);
//    }

    private void testSingleInstance() {
        TestSingleInstance singleInstance = TestSingleInstance.getInstance();
        singleInstance.setMsg("test");
        singleInstance.getMsg();
    }

    private void testSeparator() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 0);
            } else {
                System.out.println("true");
            }
        }
    }

    private void bindService() {
        //imexplicit, set Action and packageName
        Intent intent = new Intent("com.sun.androidexerciseproject.aidl");
        intent.setPackage("com.sun.androidexerciseproject");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            Log.d("sun", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("sun", "onServiceDisconnected");
            mAidlInterface = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }

    private void testMultiThread() {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
        List<Callable<Long>> tasks = new ArrayList<>();
        tasks.add(new CallableAnsyTask(arr));
        tasks.add(new CallableAnsyTask(arr));
        tasks.add(new CallableAnsyTask(arr));
        tasks.add(new CallableAnsyTask(arr));
        if (null != mPoolManager) {
            ThreadPool pool = mPoolManager.getThreadPool();
            List<Future<Long>> futures = pool.invokeAll(tasks, 1L, TimeUnit.SECONDS);
            try {
                long threadId = Thread.currentThread().getId();
                System.out.println("threadId = " + threadId);
                for (Future<Long> future : futures) {
                    Long result = null;   // 如果某个任务执行超时，调用该任务对应的future.get时抛出CancellationException异常
                    result = future.get();
                    System.out.println("并行调用，其中一个任务的执行结果为:" + result);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.show(getApplicationContext(), "Thread show text");
            }
        }).start();
    }

    public class CallableAnsyTask implements Callable<Long> {

        private int[] _arr;

        public CallableAnsyTask(int[] arr) {
            _arr = arr;
        }

        @Override
        public Long call() throws Exception {
            long threadId = Thread.currentThread().getId();
            System.out.println("threadId " + threadId);
            long result = 0;
            for (int i = 0; i < _arr.length; i++) {
                result += _arr[i];
            }
            return result;
        }
    }

    private void singletonTest() {
        EnumSingleton singleton = EnumSingleton.INSTANCE;
        singleton.init(this);
        String test = singleton.getString(android.R.string.ok);
        System.out.println("singletonTest test string = " + test);
    }

    private void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        Intent chooser = Intent.createChooser(intent, "选择应用");
        startActivityForResult(chooser, PICK_CONTACT_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (PICK_CONTACT_REQUEST == requestCode) {
            if (RESULT_OK == resultCode) {
                Uri uri = data.getData();
                String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                cursor.moveToFirst();
                int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String number = cursor.getString(column);
                System.out.println("number = " + number);
                cursor.close();
            }
        }
    }
}
